package com.htpay.util.sms;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * 描述:
 * 创瑞短信平台
 */
@Slf4j
@Component
public class ChuangRuiSmsUtil {

    private static String webUrl;
    private static String accessKey;
    private static String sign;
    private static String pwd;
    private static String templateId;

    @Value("${htpay.sms.chuangRui.web_url}")
    public void setWebUrl(String webUrl) {
        ChuangRuiSmsUtil.webUrl = webUrl;
    }

    @Value("${htpay.sms.chuangRui.accesskey}")
    public void setAccessKey(String accessKey) {
        ChuangRuiSmsUtil.accessKey = accessKey;
    }

    @Value("${htpay.sms.chuangRui.sign}")
    public void setSign(String sign) {
        ChuangRuiSmsUtil.sign = sign;
    }

    @Value("${htpay.sms.chuangRui.secret}")
    public void setPwd(String secret) {
        ChuangRuiSmsUtil.pwd = secret;
    }

    @Value("${htpay.sms.chuangRui.templateId}")
    public void setTemplateId(String templateId) {
        ChuangRuiSmsUtil.templateId = templateId;
    }


    /**
     * 发送短信到创瑞平台
     *
     * @param phone
     * @param
     * @return
     */
    public static boolean send(String phone, String code) throws Exception {
        //普通短信
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(webUrl);
        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        NameValuePair[] data = {
                new NameValuePair("accesskey", accessKey),
                new NameValuePair("secret", pwd),
                new NameValuePair("sign", sign),
                new NameValuePair("templateId", templateId),
                new NameValuePair("mobile", phone),
                new NameValuePair("content", code)//（示例模板：{1}您好，您的订单于{2}已通过{3}发货，运单号{4}）
        };
        log.info("验证码：" + code);
        postMethod.setRequestBody(data);
        postMethod.setRequestHeader("Connection", "close");

        int statusCode = httpClient.executeMethod(postMethod);
        log.info("statusCode: " + statusCode + ", body: "
                + postMethod.getResponseBodyAsString());

        return true;
    }


    /**
     * 发送短信
     *
     * @param name          用户名
     * @param pwd           密码
     * @param mobileString  电话号码字符串，中间用英文逗号间隔
     * @param contextString 内容字符串
     * @param sign          签名
     * @param stime         追加发送时间，可为空，为空为及时发送
     * @param extno         扩展码，必须为数字 可为空
     * @return
     * @throws Exception
     */
    public static String doPost(String name, String pwd,
                                StringBuffer mobileString, StringBuffer contextString,
                                String sign, String stime, StringBuffer extno, String url) throws Exception {
        StringBuffer param = new StringBuffer();
        param.append("name=" + name);
        param.append("&pwd=" + pwd);
        param.append("&mobile=").append(mobileString);
        param.append("&content=").append(URLEncoder.encode(contextString.toString(), "UTF-8"));
        param.append("&stime=" + stime);
        param.append("&sign=").append(URLEncoder.encode(sign, "UTF-8"));
        param.append("&type=pt");
        param.append("&extno=").append(extno);
        URL localURL = new URL(url);
        URLConnection connection = localURL.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(param.length()));

        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        String resultBuffer = "";

        try {
            outputStream = httpURLConnection.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);

            outputStreamWriter.write(param.toString());
            outputStreamWriter.flush();

            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }

            inputStream = httpURLConnection.getInputStream();
            resultBuffer = convertStreamToString(inputStream);

        } finally {

            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }

            if (outputStream != null) {
                outputStream.close();
            }

            if (reader != null) {
                reader.close();
            }

            if (inputStreamReader != null) {
                inputStreamReader.close();
            }

            if (inputStream != null) {
                inputStream.close();
            }

        }

        return resultBuffer;
    }

    /**
     * 转换返回值类型为UTF-8格式.
     *
     * @param is
     * @return
     */
    public static String convertStreamToString(InputStream is) {
        StringBuilder sb1 = new StringBuilder();
        byte[] bytes = new byte[4096];
        int size = 0;

        try {
            while ((size = is.read(bytes)) > 0) {
                String str = new String(bytes, 0, size, "UTF-8");
                sb1.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb1.toString();
    }
}
